package de.ff7rl.core;

import java.awt.Color;
import java.awt.Point;
import java.util.List;


public class TerminalMenu {

  public enum Orientation {
    HORIONTAL, VERTICAL
  }

  private int selectedItem;
  private final Point position;
  private final List<TerminalMenuItem> items;
  private final Orientation orientation;
  private final Game gameImpl;

  public TerminalMenu(final Game theGameImpl, final Point thePosition, final List<TerminalMenuItem> theItems) {
    this(theGameImpl, thePosition, theItems, Orientation.VERTICAL);
  }

  public TerminalMenu(final Game theGameImpl, final Point thePosition, final List<TerminalMenuItem> theItems,
      final Orientation theOrientation) {
    gameImpl = theGameImpl;
    position = thePosition;
    items = theItems;
    orientation = theOrientation;
    write();
  }

  public TerminalMenuItem getSelectedItem() {
    return items.get(selectedItem);
  }

  public void next() {
    selectedItem++;
    if (selectedItem == items.size()) {
      selectedItem = 0;
    }
    if (!getSelectedItem().isEnabled()) {
      next();
    }
    write();
  }

  public void previous() {
    selectedItem--;
    if (selectedItem == -1) {
      selectedItem = items.size() - 1;
    }
    if (!getSelectedItem().isEnabled()) {
      previous();
    }
    write();
  }

  public void write() {
    for (int i = 0; i < items.size(); i++) {
      final TerminalMenuItem item = items.get(i);
      final StringBuilder builder = new StringBuilder();
      builder.append("(");
      if (i == selectedItem) {
        builder.append("*");
      } else {
        builder.append(" ");
      }
      builder.append(") ");
      builder.append(item);
      Color color = Color.WHITE;
      if (!item.isEnabled()) {
        color = Color.GRAY;
      }
      switch (orientation) {
      case VERTICAL:
        gameImpl.getTerminal().write(position.x, position.y + i, builder.toString(), color);
        break;
      case HORIONTAL:
        // TODO implement me
        break;
      }
    }
  }

}
